package com.leetcode;

import com.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 235. 二叉搜索树的最近公共祖先
 * getPath使用非递归的写法
 * 1. 先分别找从root到p或p在树中的路径
 * 2. 通过比对路径, 找到第一个分叉的节点, 该节点就是最近公共祖先
 *
 * @author fy
 * @date 2022/4/25 21:41
 */
public class Solution235_5 {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        List<TreeNode> pPath = getPath(root, p);
        List<TreeNode> qPath = getPath(root, q);
        TreeNode ancestor = null;
        for (int i = 0; i < pPath.size() && i < qPath.size(); ++i) {
            if (pPath.get(i) == qPath.get(i)) {
                ancestor = pPath.get(i);
            } else {
                break;
            }
        }
        return ancestor;
    }

    private List<TreeNode> getPath(TreeNode root, TreeNode p) {
        if (root == null) {
            return null;
        }
        List<TreeNode> res = new ArrayList<>();
        TreeNode node = root;
        while (node != null) {
            res.add(node);
            if (node.val == p.val) {
                return res;
            } else if (node.val > p.val) {
                node = node.left;
            } else {
                node = node.right;
            }
        }
        return res;
    }

    // 另一种写法
    private List<TreeNode> getPath1(TreeNode root, TreeNode target) {
        List<TreeNode> path = new ArrayList<>();
        TreeNode node = root;
        while (node != target) {
            path.add(node);
            if (target.val < node.val) {
                node = node.left;
            } else {
                node = node.right;
            }
        }
        path.add(node);
        return path;
    }

}
